package com.seed.uaa.util;


import cn.hutool.core.util.StrUtil;
import com.seed.core.enumeration.Direction;
import com.seed.core.query.pojo.Ordered;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class OrderUtil {

    public static List<String> getOrders(List<String> orders, Map<String, Direction> orderParams) {
        List<String> ret = new ArrayList<>();
        for(String order: orders) {
            String[] items = order.split("=");
            String finalColumn = items[0];
            String value = items.length > 1 ? items[1] : null;
            if(StrUtil.isBlank(value)) {
                Direction direction = orderParams.get(finalColumn);
                if(direction != null) ret.add(String.format("%s=%s", finalColumn, direction.getValue()));
                // 客户端没提供值的忽略掉
            } else {
                ret.add(order);
            }
        }
        return ret;
    }

    public static Map<String, Ordered> merge(Map<String, Ordered> ordereds, Map<String, Ordered> others) {
        boolean isOrderedsEmpty = ordereds == null || ordereds.isEmpty();
        boolean isOthersEmpty = others == null || others.isEmpty();

        if(isOrderedsEmpty && isOthersEmpty) return new LinkedHashMap<>();

        if(isOrderedsEmpty) return others;
        if(isOthersEmpty) return ordereds;

        for(Map.Entry<String, Ordered> entry: others.entrySet()) {
            String key = entry.getKey();
            Ordered searched = ordereds.get(key);
            Ordered other = entry.getValue();
            if(searched == null) {
                ordereds.put(key, other);
                continue;
            }

            if(!searched.getType().equals(other.getType())) {
                throw new RuntimeException("类型不匹配");
            }

            merge(searched, other);
        }

        return ordereds;
    }
}
